#include <54func.h>
#include <iostream>
#include <vector>
#include <string>
#include <workflow/WFFacilities.h>
#include <workflow/HttpMessage.h>
#include <workflow/HttpUtil.h>
using std::cout;
using std::string;
struct SeriesContext{
    string url;
    size_t size;
};
static WFFacilities::WaitGroup gWaitGroup(1); 
// 阻塞主线程，直到按下ctrl+c
void handler(int signum){
    printf("signum = %d\n", signum);
    gWaitGroup.done(); //计数器减一
}
void httpCallback(WFHttpTask *httpTask){
    cout << "http callback\n";
    protocol::HttpResponse *resp = httpTask->get_resp();
    cout << resp->get_http_version() << " " 
         << resp->get_status_code() << " "
         << resp->get_reason_phrase() << "\n";
    const void * body;
    size_t size;
    resp->get_parsed_body(&body,&size);
    cout << "size = " << size << "\n";
    // 回调执行中也会写入context
    SeriesContext * context = (SeriesContext*)series_of(httpTask)->get_context();
    context->size = size;
}
void bigSeriesCallback(const SeriesWork *series){
    cout << "big series callback\n";
}
void parallelCallback(const ParallelWork * parallel){
    cout << "parallel callback\n";
    for(size_t i = 0; i < parallel->size(); ++i){
        // size() 获取序列的个数
        SeriesContext * context = (SeriesContext *) parallel->series_at(i)->get_context();
        // series_at() 找到某个序列 
        cout << "url = " << context->url << " size = " << context->size << "\n";
        delete(context);
    }
    series_of(parallel)->set_callback(bigSeriesCallback);
}
void childSeriesCallback(const SeriesWork * series){
    cout << "child series callback \n";
}
int main(){
    signal(SIGINT,handler);
    std::vector<string> vec {
        "http://www.qq.com",
        "http://www.baidu.com",
        "http://www.taobao.com"
    };
    // 创建了一个并行任务
    ParallelWork * parallel = Workflow::create_parallel_work(parallelCallback);
    for(int i = 0; i < 3; ++i){
        // 创建一个简单的http任务
        WFHttpTask* httpTask = 
        WFTaskFactory::create_http_task(vec[i],10,0,httpCallback);
        // 创建序列
        SeriesWork *series = Workflow::create_series_work(httpTask,nullptr);
        series->set_callback(childSeriesCallback);
        // 在创建序列之后，申请context
        SeriesContext * context = new SeriesContext;
        series->set_context(context);
        context->url = vec[i];
        // 把序列加入到并行任务
        parallel->add_series(series);
    }
    parallel->start(); //启动parallel
    gWaitGroup.wait(); // 等待直到计数器为0
}
